package cn.itcast.wanxinp2p.account.service.impl;

import cn.itcast.wanxinp2p.account.common.AccountErrorCode;
import cn.itcast.wanxinp2p.account.common.ConsumerErrorCode;
import cn.itcast.wanxinp2p.account.entity.Account;
import cn.itcast.wanxinp2p.api.dto.AccountDTO;
import cn.itcast.wanxinp2p.api.dto.AccountLoginDTO;
import cn.itcast.wanxinp2p.api.dto.AccountRegisterDTO;
import cn.itcast.wanxinp2p.account.mapper.AccountMapper;
import cn.itcast.wanxinp2p.account.service.AccountService;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.exception.BusinessException;
import cn.itcast.wanxinp2p.common.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SmsService smsService;

    @Value("${sms.enable}")
    private Boolean smsEnable;

    @Override
    public RestResponse getSMSCode(String mobile) {
        //TODO
        // 发起远程请求调用 短信微服务 发送短信   RestTemplate
        // http://localhost:56085/sailing/generate?effectiveTime=300&name=sms
        // {"mobile":"13566668888"}
        
        /*返回数据：直接将短信服务的结果返回即可
            {
                "code": 0,
                "msg": "",
                "result": {
                    "key": "sms:70ba933b095b4b5c90ee314045fd9003",
                    "content": null
                }
            }
         */
        // 发起远程请求调用短信微服务发送短信
        String url = "http://localhost:56085/sailing/generate?effectiveTime=300&name=sms";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<RestResponse> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, RestResponse.class);
        return RestResponse.success(responseEntity.getBody());
    }

    @Override
    public Integer checkMobile(String mobile, String key, String code) {
        /*业务逻辑：
        1、远程调用 短信微服务 校验验证码是否正确
        Post请求：
        http://localhost:56085/sailing/verify?name=sms&verificationKey=sms:70ba933b095b4b5c90ee314045fd9003&verificationCode=707339
        根据解决判断验证码校验是否成功
        2、如果验证码正确，还需要根据手机号 去 account 表中查询手机号是否存在，如果不存在，给前端返回错误信息
        smsService.verifySmsCode(key,code);
        int count = accountMapper.countByMobile(mobile);
        return count>0 ? 1:0;*/
        //校验验证码是否正确
        boolean verifyResult = smsService.verifySmsCode(key, code);
        if (!verifyResult) {
            throw new BusinessException(AccountErrorCode.E_140152);
        }
        //校验手机号是否存在
        Account account = accountMapper.countByMobile(mobile);
        return account != null ? 1 : 0;
    }

    /**
     * 账户注册
     *
     * @param registerDTO 注册信息
     * @return
     */
    @Override
    @Hmily(confirmMethod = "confirmRegister", cancelMethod = "cancelRegister")
    public AccountDTO register(AccountRegisterDTO registerDTO) {
        //TODO
        // log.info("execute tryRegister");

        // 1、校验手机号是否存在
        Account accountM = accountMapper.countByMobile(registerDTO.getMobile());
        if (accountM != null) {
            throw new BusinessException(ConsumerErrorCode.E_140105);
        }
       // int i = 10/0;
        // 2、保存账号信息到account表中
        Account account = new Account();
        account.setUsername(registerDTO.getUsername());
        account.setMobile(registerDTO.getMobile());
        account.setPassword(registerDTO.getPassword());
        account.setDomain("c");
        accountMapper.insertSelective(account);
        // 4、返回账号信息
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setUsername(account.getUsername());
        accountDTO.setDomain(account.getDomain());
        accountDTO.setMobile(account.getMobile());
        return accountDTO;

    }
    public void confirmRegister(AccountRegisterDTO registerDTO) {
        log.info("execute confirmRegister");
    }

    public void cancelRegister(AccountRegisterDTO registerDTO) {
        log.info("execute cancelRegister");
        //TODO 删除账号
        accountMapper.deleteAccount(registerDTO.getUsername());

    }

    @Override
    public AccountDTO login(AccountLoginDTO accountLoginDTO) {
        //1、查询用户，注意此处需要根据前端传递的 AccountLoginDTO的domain做判断：
        //  如果值是 c 表示是c端用户，需要根据手机号查询
        //  否则是b端用户，需要根据用户名查询
        //2、判断用户是否存在，如果不存在，直接抛出 AccountErrorCode.E_130104 异常
        //3、如果 smsEnable=true ，说明是短信验证码登录，不做密码校验。直接返回
        //4、验证密码，如果密码错误则抛出 AccountErrorCode.E_130105 异常
        //1、查询用户，注意此处需要根据前端传递的 AccountLoginDTO 的 domain 做判断：
        //  如果值是 c 表示是 c 端用户，需要根据手机号查询
        //  否则是 b 端用户，需要根据用户名查询
        Account account;
        if ("c".equals(accountLoginDTO.getDomain())) {
            account = accountMapper.countByMobile(accountLoginDTO.getMobile());
        } else {
            account = accountMapper.countByUserName(accountLoginDTO.getUsername());
        }

        //2、判断用户是否存在，如果不存在，直接抛出 AccountErrorCode.E_130104 异常
        if (account == null) {
            throw new BusinessException(AccountErrorCode.E_130104);
        }

        //3、如果 smsEnable=true ，说明是短信验证码登录，不做密码校验。直接返回
        if (smsEnable) {
            AccountDTO accountDTO = new AccountDTO();
            BeanUtils.copyProperties(account, accountDTO);
            return accountDTO;
        }

        //4、验证密码，如果密码错误则抛出 AccountErrorCode.E_130105 异常
        if (PasswordUtil.verify(accountLoginDTO.getPassword(),account.getPassword())) {
            throw new BusinessException(AccountErrorCode.E_130105);
        }

        //5、将 Account 转换为 AccountDTO 并返回
        AccountDTO accountDTO = new AccountDTO();
        BeanUtils.copyProperties(account, accountDTO);
        return accountDTO;
    }
}


